﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RadarGlobal.UIView;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;

namespace RadarGlobal
{
    class Global
    {
        public static User UserInfo = new User();

        public static void DeleteSettings()
        {
            using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isoStorage.FileExists("Userlogin.xml"))
                {
                    isoStorage.DeleteFile("Userlogin.xml");
                }
            }
        }
        public static void SaveSettings()
        {
            XmlWriterSettings xmlWriterSetting = new XmlWriterSettings();

            xmlWriterSetting.Indent = true;
            // Lấy thông tin IsolateStorage
            using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Tạo một FileStream để tạo file hay mở file
                using (IsolatedStorageFileStream Stream = new IsolatedStorageFileStream("Userlogin.xml", System.IO.FileMode.Create, isoStorage))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(User));

                    using (XmlWriter xmlWriter = XmlWriter.Create(Stream, xmlWriterSetting))
                    {
                        // Viết dữ liệu theo Serialize
                        serializer.Serialize(xmlWriter, Global.UserInfo);
                    }
                }
            }
        }

        public static void LoadSettings()
        {
            using (IsolatedStorageFile File = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (File.FileExists("Userlogin.xml"))
                {
                    using (IsolatedStorageFileStream FileStream = new IsolatedStorageFileStream("Userlogin.xml", System.IO.FileMode.Open, File))
                    {
                        try
                        {
                            // Trong FileStream thực hiện Deserialize
                            XmlSerializer serialize = new XmlSerializer(typeof(User));
                            // Ép kiểu về đúng kiểu ban đầu và Gán lại cho Source 
                            Global.UserInfo = (User)serialize.Deserialize(FileStream);
                        }
                        catch (Exception ex)
                        {
                            FileStream.Close();

                            //File.DeleteFile("Userlogin.xml");
                        }
                    };
                };
            }
        }
    }
}
